<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise</title>
</head>
<body>
    <img src="../Image/bg/1.jpg" alt="" onload="console.log('加载完成')" onerror="console.log('default')">
    <script>
        // const promise = new Promise(function(resolve, reject) {

        //     if(true) {
        //         resolve(value);
        //     } else {
        //         reject(error);
        //     }
        // })

        // let promise1 = new Promise(function(resolve, reject) {
        //     console.log('Promise');
        //     resolve();
        // });
        // promise1.then(function() {
        //     console.log('Resolve');
        // }, function() {
        //     console.log('Rejected');
        // });
        // // then 里的内容都要在同步任务执行完才会执行
        // console.log('Hi');

        // 图片异步加载
        function loadImageAsync(url) {
            return new Promise(function(resolve, reject) {
                const image = new Image();

                image.onload = function () {
                    resolve(image);
                };

                image.onerror = function () {
                    reject(new Error('Could not load image at' + url));
                };

                image.src = url;
            });
        }

        LoadImage('../Image/bg/1.jpg').then(function(img) {
            console.log(img);
            document.getElementsByTagName('body')[0].append(img);
        }, function (error) {
            console.log(error);
        });

        function LoadImage(url) {
            return new Promise(function(resolve, reject) {
                let img = new Image(100, 200);
                img.src = url;
                // img.onload(resolve(img));
                img.onload(function () {
                    resolve(img);
                })

                img.onerror(function () {
                    reject('error');
                });
            })
        }

    </script>
</body>
</html>